package com.goods.shop.service.file;

import cn.hutool.core.codec.Base64;
import com.goods.shop.service.AbstractService;

import java.io.*;

public class FileServiceImpl extends AbstractService implements FileService {
    @Override
    public void changeToEncodeFile(String sourceFile, String destFile) {
        BufferedReader reader=null;
        BufferedWriter writer=null;
        String line=null;
        try {
            reader=new BufferedReader(new InputStreamReader(new FileInputStream(sourceFile),"UTF-8"));
            writer=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(destFile),"UTF-8"));
            while((line=reader.readLine())!=null){
                String encodeLine= Base64.encode(line.getBytes("UTF-8"));
                writer.write(encodeLine);
                writer.newLine();

            }
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(reader!=null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(writer!=null){
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void changeToDecodeFile(String sourceFile, String destFile) {
        BufferedReader reader=null;
        BufferedWriter writer=null;
        String line=null;
        try {
            reader=new BufferedReader(new InputStreamReader(new FileInputStream(sourceFile),"UTF-8"));
            writer=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(destFile),"UTF-8"));
            while((line=reader.readLine())!=null){
                byte[] datas=Base64.decode(line);
                String encodeLine= new String(datas,"UTF-8");
                writer.write(encodeLine);
                writer.newLine();
            }
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(reader!=null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(writer!=null){
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        FileService fileService=new FileServiceImpl();
        String sourceFile="D:/HTTPTEST";
        String destFile="D:/HttpRequest.java";
        fileService.changeToDecodeFile(sourceFile,destFile);



//        String sourceFile="D:/xnlp.csv";
//        String destFile="D:/xnlp-source.csv";
//        fileService.changeToDecodeFile(sourceFile,destFile);
    }
}
